//
//  ToBeReviewedTaskListViewController.m
//  MyProject
//
//  Created by Pei on 16/7/18.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "ToBeReviewedTaskListViewController.h"
#import "IHRefreshTableView.h"
#import "TaskManagerCell.h"
#import "CreateTaskViewController.h"
#import "NSMutableArray+Additions.h"
#import "UserInfo.h"
#import "SelectModel.h"
#import "ToBeSureTaskViewController.h"
#import "ToBeReviewedTaskDetailViewController.h"

@interface ToBeReviewedTaskListViewController ()<UITableViewDataSource,UITableViewDelegate,IHTableViewRefreshingDelegate, ToBeSureTaskViewControllerDelegate>
{
    MySceneType _type;
    
    IHRefreshTableView *_myTable;
    
    UIView *_addView;
    
    UIControl *_addControl;
    
    UIButton *_rightBtn;
    
    NSArray *_contentArray;
    
    NSDictionary *_currentDic;
    
    NSString *_currentStr;
}

@end

@implementation ToBeReviewedTaskListViewController

- (id)initWith:(MySceneType)type
{
    self = [super init];
    if (self)
    {
        _type = type;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:Hide_TabBar_Notification object:nil];
    
    //_contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
    //[_myTable reloadData];
}

- (void)getData
{
    [[YMNetLib getInstance] connectWithAction:Get_ToBeReviewed_Task_List method:@"GET" withContent:@"" withBody:nil withDelegate:self];
    _currentStr = Get_ToBeReviewed_Task_List;
}

- (void)NetDoOverSuccess:(NSDictionary*)body
{
    if ([_currentStr isEqualToString:@"Check_Type_Items"]) {
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1){
            [[NSUserDefaults standardUserDefaults] setObject:[body valueForKey:@"DicList"] forKey:Check_Type_Items];
            [_myTable reloadData];
        }
    }else{

    if ([[YMNetDataUtil getSuccessState:body] intValue] == 1)
    {
        _currentDic = body;
        
        _contentArray = [_currentDic valueForKey:@"PenddingAuditList"];
        [_myTable reloadData];
        
        NSArray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:Check_Type_Items];
        if (tempArray != nil && tempArray.count > 0) {
            
        }else{
            [self getCheckData];
        }
    }
    }
}

- (void)getCheckData{
    [[YMNetLib getInstance] connectWithAction:Dictionary_Type_API method:@"GET" withContent:@"DicType=InspectType" withBody:nil withDelegate:self];
    _currentStr = @"Check_Type_Items";
}

- (void)viewDidLoad {
    self.navTitle = @"待审核任务";
    [super viewDidLoad];
        
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getData) name:@"Reload_ToBeReviewed_LIst" object:nil];

    
    _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 22)];
    //[rightBtn setBackgroundImage:[UIImage imageNamed:@"02edit"] forState:UIControlStateNormal];
    //[rightBtn setBackgroundImage:[UIImage imageNamed:@"02edit"] forState:UIControlStateHighlighted];
    [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_rightBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [_rightBtn addTarget:self action:@selector(rightBtnAcion) forControlEvents:UIControlEventTouchUpInside];
    //[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
    
    
    
    [self initTableView];
    
    _addControl = [[UIControl alloc] init];
    _addControl.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    [_addControl addTarget:self action:@selector(addControlAction) forControlEvents:UIControlEventTouchUpInside];
    _addControl.backgroundColor = kBtnBackgroundColor;
    //[self.view addSubview:_addControl];
    
    //02edit@3x
    UILabel *btnTitle = [[UILabel alloc] initWithFrame:CGRectMake((kDeviceWidth-66)/2.0f, (_addControl.height-Home_Big_Size)/2.0f, 66, Home_Big_Size)];
    btnTitle.textColor = kWhiteColor;
    btnTitle.text = @"添加任务";
    btnTitle.font = kAppFont(Home_Big_Size);
    [_addControl addSubview:btnTitle];
    
    _addView = [[UIView alloc] init];
    _addView.hidden = YES;
    _addView.frame = CGRectMake(0.0f, kDeviceHeight-NAV_HEIGHT-kTabHeight, kDeviceWidth, kTabHeight);
    //[self.view addSubview:_addView];
    
    //114 122 162
    UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(0.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [cancleBtn setBackgroundColor:kRGB(114, 122, 162)];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    cancleBtn.titleLabel.font = kAppFont(Home_Big_Size);
    cancleBtn.tag = 116;
    [cancleBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_addView addSubview:cancleBtn];
    
    UIButton *uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    uploadBtn.frame = CGRectMake(kDeviceWidth/3.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [uploadBtn setBackgroundColor:kBtnBackgroundColor];
    [uploadBtn setTitle:@"提交" forState:UIControlStateNormal];
    [uploadBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    uploadBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [uploadBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    uploadBtn.tag = 118;
    [_addView addSubview:uploadBtn];
    
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(kDeviceWidth/3.0f*2.0f, 0.0f, kDeviceWidth/3.0f, kTabHeight);
    [deleteBtn setBackgroundColor:kRedColor];
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    deleteBtn.titleLabel.font = kAppFont(Home_Big_Size);
    deleteBtn.tag = 119;
    [deleteBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [_addView addSubview:deleteBtn];
    
    [self getData];
}

#pragma mark **************************** UI *********************************
- (void)initTableView
{
    CGRect frame = CGRectMake(0, 0.0f, kDeviceWidth, kDeviceHeight-NAV_HEIGHT);
    _myTable = [[IHRefreshTableView alloc] initWithFrame:frame refreshType:-1 andAutoLoad:NO];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    _myTable.refreshDelegate = self;
    _myTable.footer.hidden = YES;
    _myTable.header.hidden = YES;
    _myTable.allowsSelectionDuringEditing = YES;
    [self.view addSubview:_myTable];
}

#pragma mark ************************** Action ************************
- (void)rightBtnAcion
{
    [_myTable setEditing:!_myTable.editing animated:YES];
    
    _addControl.hidden = YES;
    _addView.hidden = NO;
    
    [self.navigationItem setRightBarButtonItem:nil];
}

- (void)addControlAction
{
    CreateTaskViewController *createTaskVC = [[CreateTaskViewController alloc] init];
    [self.navigationController pushViewController:createTaskVC animated:YES];
}


- (void)btnAction:(UIButton*)sender
{
    switch (sender.tag) {
        case 116:
        {
            [_myTable setEditing:!_myTable.editing animated:YES];
            
            _addView.hidden = YES;
            _addControl.hidden = NO;
            
            [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:_rightBtn]];
        }
            break;
        case 119:
        {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
            for (int i = 0; i < _contentArray.count; i++)
            {
                NSDictionary *tempD = [_contentArray objectAtIndex:i];
                if ([[tempD valueForKey:@"isSelect"] boolValue]) {
                    //[tempArray replaceObjectAtIndex:i withObject:@""];
                    [tempArray removeObject:tempD];
                }
            }
            _contentArray = tempArray;
            
            [[NSUserDefaults standardUserDefaults] setObject:_contentArray forKey:Create_Task];
            _contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
            
            [_myTable reloadData];
            
            
        }
            break;
        case 118:
        {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
            for (int i = 0; i < _contentArray.count; i++)
            {
                NSDictionary *tempD = [_contentArray objectAtIndex:i];
                if ([[tempD valueForKey:@"isSelect"] boolValue]) {
                    //[tempArray replaceObjectAtIndex:i withObject:@""];
                    [self uploadTask:tempD];
                    //[tempArray removeObject:tempD];
                }
            }
            _contentArray = tempArray;
            
            [[NSUserDefaults standardUserDefaults] setObject:_contentArray forKey:Create_Task];
            _contentArray = (NSArray*)[[NSUserDefaults standardUserDefaults] objectForKey:Create_Task];
            
            
        }
            break;
        default:
            break;
    }
}


- (void)uploadTask:(NSDictionary*)tempD
{
    NSMutableArray *InspectTaskListArray = [[NSMutableArray alloc] initWithCapacity:3];
    NSArray *tempA = [tempD objectForKey:@"InspectionItems"];
    for (NSDictionary *tempD in tempA) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:3];
        [dic setValue:[tempD valueForKey:@"InspectContentID"] forKey:@"InspectItemCode"];
        [dic setValue:[tempD valueForKey:@"InspectContentName"] forKey:@"InspectTaskName"];
        [dic setValue:@"" forKey:@"DeadLineDate"];
        [InspectTaskListArray addObject:dic];
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:[tempD valueForKey:@"InspectDate"]];
    
    //Upload_Task
    NSDictionary *bodyDic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [[UserInfo getInstance] getUserID],@"UserID",//UserID
                             [tempD valueForKey:@"InspectionNo"],@"InspectionNo", //检查单号
                             [NSNumber numberWithInt:[[[tempD objectForKey:@"InspectType"] valueForKey:@"Value"] intValue]], @"InspectType", //检查类型 int  {Code = "SQCP_Security_InspectionType_Daily"; Name = "\U65e5\U5e38\U68c0\U67e5"; Value = 0;},
                             //{"projectCode":"XM201611","orgCode":"YFZX","orgName":"公司本部","unitCode":"region","unitName":"三航局","projectName":"青岛项目部"}
                             [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"orgCode"], @"InspectOrgCode", //被检查公司编码
                             [[tempD objectForKey:@"InspectOrgAndProject"] valueForKey:@"projectCode"], @"InspectProjectCode", //被检查项目编码
                             date, @"InspectDate", //检查时间 DateTime
                             [NSNumber numberWithInt:[[tempD valueForKey:@"InspectionState"] intValue]], @"InspectionState", //检查单状态 int
                             [tempD valueForKey:@"InspectionRemark"], @"InspectionRemark", //检查单备注
                             InspectTaskListArray,@"InspectTaskList",
                             nil];
    [[YMNetLib getInstance] connectWithAction:Upload_Task method:@"POST" withContent:nil withBody:bodyDic withDelegate:self];
    
}

//- (void)NetDoOverSuccess:(NSDictionary*)body
//{
//
//
//    NSLog(@"========error%@",[body valueForKey:@"Error"]);
//}


#pragma mark  ************************* UITableViewDataSource **************************************
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id ddd = [_currentDic valueForKey:@"PenddingAuditList"];
    if ([ddd isKindOfClass:[NSString class]]) {
        if ([[_currentDic valueForKey:@"PenddingAuditList"] isEqualToString:@""]) {
            return 0;
        }
    }
    
    return (nil == _contentArray) ? 0 : _contentArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"TaskManagerCell";
    /*
     TaskManagerCell *cell = (TaskManagerCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
     if (cell == nil)
     {
     cell = [[TaskManagerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
     }
     cell.selectionStyle = UITableViewCellSelectionStyleNone;
     [cell showWithData:nil];
     return cell;
     */
    TaskManagerCell *cell = (TaskManagerCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[TaskManagerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundView = [[UIView alloc] init];
    }
    NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
    //cell.mSelected = [(NSNumber *)[tempDic objectForKey:@"isSelect"] boolValue];
    
    [cell showWithDataToBeReviewed:tempDic];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //[_selFlags moveObjectFromIndex:sourceIndexPath.row toIndex:destinationIndexPath.row];
}


#pragma mark -
#pragma mark Table view delegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
    
    if (tableView.isEditing)
    {
        /*
         TaskManagerCell *cell = (TaskManagerCell *)[tableView cellForRowAtIndexPath:indexPath];
         [cell changeMSelectedState];
         NSDictionary *tempDic = [_contentArray objectAtIndex:indexPath.row];
         NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:_contentArray];
         for (int i = 0; i < tempArray.count; i++)
         {
         NSMutableDictionary *tempD = [[NSMutableDictionary alloc] initWithDictionary:[tempArray objectAtIndex:i]];
         if ([[tempDic valueForKey:@"InspectionNo"] isEqualToString:[tempD valueForKey:@"InspectionNo"]]) {
         //[NSNumber numberWithBool:YES], @"isSelect"
         //[tempD setValue:@"1" forKey:@"isSelect"];
         //[tempD removeObjectForKey:@"isSelect"];
         [tempD setObject:[NSNumber numberWithBool:cell.mSelected] forKey:@"isSelect"];
         [tempArray replaceObjectAtIndex:i withObject:tempD];
         }
         }
         _contentArray = tempArray;
         */
    }
    else
    {
        ToBeReviewedTaskDetailViewController *sureVC = [[ToBeReviewedTaskDetailViewController alloc] initWithDic:tempDic];
        //sureVC.delegate = self;
        [self.navigationController pushViewController:sureVC animated:YES];
    }
}

- (void)refreshData
{
    [self getData];
}

@end
